package cn.tq.pethome.dept.service.impl;

import cn.tq.pethome.base.service.impl.BaseServiceImpl;
import cn.tq.pethome.dept.domain.Department;
import cn.tq.pethome.dept.mapper.IDepartmentMapper;
import cn.tq.pethome.dept.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private IDepartmentMapper departmentMapper;


    @Transactional
    @Override
    public void insert(Department dept) {
        departmentMapper.insert(dept);
        //修改
        this.update(dept);
    }

    @Transactional
    @Override
    public void update(Department dept) {
        String dirPath ="";
        if (dept.getParent() != null){
            //获取父级部门的id
            Long id = dept.getParent().getId();
            //从数据库里查询出来父类对象
            Department parentDept = this.findById(id);
            //从数据库里查询出父级部门路径
            dirPath = parentDept.getDirPath();
        }
        //获取自己的id
        Long id = dept.getId();
        //拼接路径
        dirPath = dirPath +"/"+ id;
        //设置到自己路径中
        dept.setDirPath(dirPath);
        departmentMapper.update(dept);
    }

    @Override
    public List<Department> getTree() {
        List<Department> deptAll = departmentMapper.findAll();
        List<Department> firstDept = new ArrayList<>();
        for (Department department : deptAll) {
            //判断是否是顶级部门
            if (department.getParent_id() == null){
                firstDept.add(department);
            }else {
                for (Department parentDept : deptAll) {
                    if (parentDept.getId() == department.getParent_id()){
                        parentDept.getChildren().add(department);
                    }
                }
            }
        }
        return firstDept;

    }
}
